
package LoadFromDatabase;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LineString;

import gao.tools.SQL;
import java.sql.Statement;
import java.sql.ResultSet;

public class LoadStreetsFromDB extends Thread {
    
    private Statement statement;
    private Envelope boundingBox;
    private Geometry square;

    public LoadStreetsFromDB(Statement statement, Envelope boundingBox, Geometry square){
        this.statement = statement;
        this.boundingBox = boundingBox;
        this.square = square;
    }
    
    @Override
    public void run(){
        String data = "";
        try{
            System.out.println("Start Loading Streets");
            ResultSet resultSet = statement.executeQuery("SELECT realname, geodata_line, gao_id FROM domain WHERE geometry='L' AND lsiclass BETWEEN 35000 AND 35999 AND"+
                    SQL.createIndexQuery(boundingBox.getMaxX(),boundingBox.getMaxY(),boundingBox.getMinX(),boundingBox.getMinY(),SQL.COMPLETELY_INSIDE));
            System.out.println("Finished Loading Streets");
            System.out.println("Start Writing File Streets");
            while(resultSet.next()){
                String realname = resultSet.getString(1);
                byte[] geodata_line = resultSet.getBytes(2);
                Geometry geom=SQL.wkb2Geometry(geodata_line);
                String gao_id = resultSet.getString(3);
                if (geom.within(square)) { // Exact geometrisch testen, ob die Geometry im Quadrat liegt
                	if(geom instanceof LineString){
                        LineString linestring=((LineString)geom);
                        int n=linestring.getNumPoints();
                        for (int i=0;i<n;i++)
                        {
                             Coordinate coord=linestring.getCoordinateN(i);
                             data += coord.x + "," + coord.y + " ";
                        }
                		data += ";" + gao_id + "\r\n";
                	}
                }
            }
            resultSet.close();
        }catch(Exception ex){
            System.out.println("Error in Execute Query Streets: "+ex.toString());
            ex.printStackTrace();
            System.exit(1);
        }    
        WriteData.write(data, FileNames.fileNameStreets);
        System.out.println("Finished Writing File Streets");
    }
}
